<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="项目名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px"
        />
      </el-form-item>
      <el-form-item label="负责人" prop="projectLeaderName">
        <el-input
          v-model="queryParams.projectLeaderName"
          placeholder="负责人姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px"
        />
      </el-form-item>
      <el-form-item label="指导老师" prop="supervisor">
        <el-input
          v-model="queryParams.supervisor"
          placeholder="指导老师"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="reviewStatus" style="width: 180px">
        <el-select v-model="queryParams.reviewStatus" placeholder="审核状态">
          <el-option label="未审核" value="0" />
          <el-option label="审核通过" value="1" />
          <el-option label="审核不通过" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目状态" prop="projectStatus" style="width: 180px">
        <el-select v-model="queryParams.projectStatus" placeholder="项目状态">
          <el-option label="进行中" value="0" />
          <el-option label="已完成" value="1" />
          <el-option label="审核通过" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:project:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:project:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:project:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:project:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="projectList"
      @selection-change="handleSelectionChange"
      empty-text="暂无数据"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识" align="center" prop="id" width="50" />
      <el-table-column label="项目的名称" align="center" prop="projectName" />
      <!-- <el-table-column label="项目图片" align="center" prop="image" width="100">
        <template #default="scope">
          <el-image 
            v-if="scope.row.image" 
            :src="scope.row.image" 
            :preview-src-list="[scope.row.image]"
            style="width: 50px; height: 50px"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column> -->

      <!--   <el-table-column label="项目的详细描述" align="center" prop="projectDescription" /> -->
      <!-- <el-table-column label="负责人学号" align="center" prop="projectLeaderId" /> -->
      <el-table-column label="负责人姓名" align="center" prop="projectLeaderName" />
      <el-table-column label="负责人联系方式" align="center" prop="projectLeaderLink" />
      <el-table-column label="指导老师" align="center" prop="supervisor" />
      <el-table-column label="人数限制" align="center" prop="teamSize" />
      <el-table-column label="项目申请状态" align="center" prop="reviewStatus">
        <template #default="scope">
          <span>{{
            scope.row.reviewStatus === "0"
              ? "未审核"
              : scope.row.reviewStatus === "1"
              ? "审核通过"
              : "审核不通过"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目完成状态" align="center" prop="projectStatus">
        <template #default="scope">
          <span>{{
            String(scope.row.projectStatus) === "0"
              ? "进行中"
              : String(scope.row.projectStatus) === "1"
              ? "已完成"
              : String(scope.row.projectStatus) === "2"
              ? "审核通过"
              : scope.row.projectStatus || "-"
          }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="项目总分值" align="center" prop="totalScore">
        <template #default="scope">
          <span>{{
            String(scope.row.projectStatus) === "2"
              ? (scope.row.totalScore || "0")
              : "暂不能修改"
          }}</span>
        </template>
      </el-table-column>

      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:project:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:project:remove']"
            >删除</el-button
          >
          <el-button
            link
            type="success"
            icon="Operation"
            @click="handleProjectNameClick(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目的名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="projectDescription">
          <el-input
            v-model="form.projectDescription"
            placeholder="请输入项目的详细描述"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="项目图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-change="handleImageChange"
            :show-file-list="false"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人" prop="projectLeaderName">
          <el-input v-model="form.projectLeaderName" placeholder="请输入项目负责人姓名" />
        </el-form-item>
        <el-form-item label="学号" prop="projectLeaderId">
          <el-input v-model="form.projectLeaderId" placeholder="请输入项目负责人学号" />
        </el-form-item>
        <el-form-item label="联系方式" prop="projectLeaderLink">
          <el-input v-model="form.projectLeaderLink" placeholder="请输入负责人联系方式" />
        </el-form-item>
        <el-form-item label="指导老师" prop="supervisor">
          <el-input v-model="form.supervisor" placeholder="请输入项目的指导老师" />
        </el-form-item>
        <el-form-item label="人数限制" prop="teamSize">
          <el-input v-model="form.teamSize" placeholder="请输入参与项目的人数限制" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-select v-model="form.reviewStatus" placeholder="请选择审核状态">
            <el-option label="未审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核不通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目状态" prop="projectStatus">
          <el-select v-model="form.projectStatus" placeholder="请选择项目状态">
            <el-option label="进行中" value="0" />
            <el-option label="已完成" value="1" />
            <el-option label="审核通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目仓库" prop="projectRepository">
          <el-input v-model="form.projectRepository" placeholder="请输入项目仓库" />
        </el-form-item>

        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <!-- <el-form-item label="项目开始时间" prop="startDate">
          <el-date-picker
            clearable
            v-model="form.startDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择项目开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目结束时间" prop="endDate">
          <el-date-picker
            clearable
            v-model="form.endDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择项目结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建时间" prop="createdTime">
          <el-date-picker
            clearable
            v-model="form.createdTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="createdBy">
          <el-input v-model="form.createdBy" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="更新人" prop="updatedBy">
          <el-input v-model="form.updatedBy" placeholder="请输入更新人" />
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime">
          <el-date-picker
            clearable
            v-model="form.updatedTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更新时间"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="总分值" prop="totalScore">
          <el-input
            v-model="form.totalScore"
            placeholder="请输入项目总分值(项目完成后填写)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
} from "@/api/projectmanagement/project";
import { useRouter } from "vue-router";
import { uploadImageFile } from "@/api/tool/oss";
import { Plus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const router = useRouter();

const projectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    projectDescription: null,
    projectLeaderId: null,
    projectLeaderName: null,
    projectLeaderLink: null,
    supervisor: null,
    teamSize: null,
    reviewStatus: null,
    totalScore: null,
    projectStatus: null,
    startDate: null,
    endDate: null,
    createdTime: null,
    createdBy: null,
    updatedBy: null,
    updatedTime: null,
    remark: null,
    image: null,
    projectRepository: null
  },
  rules: {},
  imageFile: null,
});

const { queryParams, form, rules } = toRefs(data);

/** 查询项目列表 */
function getList() {
  loading.value = true;
  listProject(queryParams.value).then((response) => {
    projectList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectName: null,
    projectDescription: null,
    projectLeaderId: null,
    projectLeaderName: null,
    projectLeaderLink: null,
    supervisor: null,
    teamSize: null,
    reviewStatus: null,
    totalScore: null,
    projectStatus: null,
    delFlag: null,
    startDate: null,
    endDate: null,
    createdTime: null,
    createdBy: null,
    updatedBy: null,
    updatedTime: null,
    remark: null,
    image: null,
    projectRepository: null
  };
  data.imageFile = null;
  proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加项目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getProject(_id).then((response) => {
    form.value = response.data;
    // 确保projectStatus为字符串类型，以便下拉框正确显示文字
    if (form.value.projectStatus !== null && form.value.projectStatus !== undefined) {
      form.value.projectStatus = String(form.value.projectStatus);
    }
    open.value = true;
    title.value = "修改项目";
  });
}

// 处理图片上传
function handleImageChange(file) {
  data.imageFile = file.raw;
  // 创建临时URL用于预览
  form.value.image = URL.createObjectURL(file.raw);
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate((valid) => {
    if (valid) {
      // 提示正在提交中
      proxy.$modal.loading("正在提交中...");
      // 如果有图片文件，先上传图片
      if (data.imageFile) {
        uploadImageFile(data.imageFile).then(response => {
          // 图片上传成功后，将图片URL添加到表单数据中
          form.value.image = response.msg;
          submitProjectData();
        }).catch(error => {
          // 关闭提交中的提示
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("图片上传失败");
        });
      } else {
        // 没有图片直接提交项目数据
        submitProjectData();
      }
    }
  });
}

/** 提交项目数据 */
function submitProjectData() {
  if (form.value.id != null) {
    updateProject(form.value)
      .then((response) => {
        // 关闭提交中的提示
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      })
      .catch(() => {
        // 关闭提交中的提示
        proxy.$modal.closeLoading();
      });
  } else {
    addProject(form.value)
      .then((response) => {
        // 关闭提交中的提示
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      })
      .catch(() => {
        // 关闭提交中的提示
        proxy.$modal.closeLoading();
      });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除项目编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delProject(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

/** 项目名称点击事件 */
function handleProjectNameClick(row) {
  // 跳转到项目详情页面，传递项目ID作为参数
  router.push({
    path: "/projectmanagement/detail",
    query: { id: row.id },
  });
}

getList();
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
